/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.service.render;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Simple LRU Cache implementation, based on a {@linkplain LinkedHashMap}.
 * <p/>
 * <h3>Extra-Info</h3>
 * Created: 00:46 30.07.11
 *
 * @author Burt Parkers
 * @version 1.0
 */
public class LRUCache<S, T> {

    /** Default size of the cache. */
    private static final int MAX_CACHE_SIZE = 10;
    /** The cache itself. */
    private Map<S, T> cache;

    /** Creates a cache instance with default size. */
    public LRUCache() {
        this(MAX_CACHE_SIZE);
    }

    /**
     * Creates a cache instance with a user defined size.
     *
     * @param size the cache size.
     */
    public LRUCache(final int size) {
        cache = new LinkedHashMap<S, T>(size + 1, 0.70f, true) {
            @Override
            public boolean removeEldestEntry(Map.Entry eldest) {
                return size() > size;
            }
        };
    }

    /**
     * Add a new entry to the cache.
     *
     * @param s the key.
     * @param t the value
     */
    public void put(S s, T t) {
        cache.put(s, t);
    }

    /**
     * Returns a cached entry.
     *
     * @param s the key.
     * @return the value if exists, otherwise null.
     */
    public T get(S s) {
        return cache.get(s);
    }
}
